package org.hibernate.test.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.test.dao.UserDao;
import org.hibernate.test.dto.UserDto;
import org.spring.test.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service(value="userService")
@Transactional(propagation = Propagation.REQUIRED)
public class UserService implements IService<UserDto> {

	@Autowired(required = false)
	@Qualifier("userRepository")
	private UserDao userRepository;
	
	@Autowired
	private MessageDigestPasswordEncoder passwordEncoder;
	
	@Autowired 
	private SaltSource saltSource;


	@Override
	public List<UserDto> listAll() {
		return userRepository.listAll();
	}

	@Override
	public UserDto getById(Long id) {
		return userRepository.getById(id);
	}

	@Override
	public UserDto saveOrUpdate(UserDto user) {
		return userRepository.saveOrUpdate(user);
	}

	@Override
	public void delete(UserDto user) {
		userRepository.delete(user);
	}

	@Override
	public Integer count() {
		return userRepository.count();
	}
	public UserDto findUserByNickName(String nick){
		return userRepository.findUserByNickName(nick);
	}
	
	public boolean changeUserPassword(String newPassword){
		CustomUserDetails user = (CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		UserDto userdto =userRepository.getById(user.getIdUser());
		userdto.setPassword(passwordEncoder.encodePassword(newPassword,  saltSource.getSalt(user)));
		userRepository.saveOrUpdate(userdto);
		return false;
	}

	public void createUser(){
		CustomUserDetails user = new CustomUserDetails("admin", "12345", true, true, true, true, new ArrayList<GrantedAuthority>());
		System.err.println(passwordEncoder.encodePassword("12345", saltSource.getSalt(user)));
	}
}
